package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Engine engine;

    public RequestProcessor(Socket socket, Engine engine) {
        this.socket = socket;
        this.engine = engine;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            String requestUrl = request.getUrl();

            List<Host> hosts = engine.getHosts();

            hosts.forEach(host -> {
                List<Context> contexts = host.getContexts();
                contexts.stream()
                        .filter(context -> {
                            String path = "/" + context.getContext();
                            return requestUrl.startsWith(path);
                        })
                        .forEach(context -> {
                            String path = "/" + context.getContext();
                            String uri = requestUrl.substring(path.length());
                            List<Wrapper> wrappers = context.getWrappers();
                            wrappers.stream().filter(wrapper -> {
                                String pattern = wrapper.getPattern();
                                return Pattern.compile(pattern).matcher(uri).matches();
                            }).forEach(wrapper -> {
                                try {
                                    wrapper.getServlet().service(request, response);
                                } catch (Exception exception) {
                                    exception.printStackTrace();
                                }
                            });

                        });
            });


//            // 静态资源处理
//            if(servletMap.get(request.getUrl()) == null) {
//                response.outputHtml(request.getUrl());
//            }else{
//                // 动态资源servlet请求
//                HttpServlet httpServlet = servletMap.get(request.getUrl());
//                httpServlet.service(request,response);
//            }

            socket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
